# FILE: WebDocumentNodeLoader.py
# DESC: loads webdocument records from db
#

import MySQLdb

from geo.manager.DestinationNodeLoader import DestinationNodeLoader
from infra.db import DBManager
from web.entity.WebDocumentNode import WebDocumentNode
from infra.logging import logger

class WebDocumentNodeLoader(DestinationNodeLoader):

	def __init__(self, customer):
		DestinationNodeLoader.__init__(self, customer, 'webdocument')
		self.geonameWebDocMap_ = {}
		self.webDocMap_ = {}

	def load(self):			
		try:
			log = logger.getLogger()
			webDocCursor = DBManager.getCursor()
			
			webDocCursor.execute("SELECT gp.geoname_id, gp.text_before, gp.text_after, gp.weight, \
								  wd.id, wd.images, wd.name, wd.url, wd.price \
				                  FROM webdocument wd, geoplacemark gp \
			    	              WHERE gp.customer_id = %s \
			        	          AND gp.webdocument_id = wd.id", \
			            			    self.customer_.getId())
			
			webDocRecs = webDocCursor.fetchall()
			log.debug('fetched %d webdocument records' % len(webDocRecs))

			
			for webDocRec in webDocRecs:
				geonameId = webDocRec[0]
				webDocId = webDocRec[4]
				
				if not self.webDocMap_.has_key(webDocId):
					self.webDocMap_[webDocId] = WebDocumentNode(webDocRec[4:], self.customer_.getUrl())
				
				if self.geonameWebDocMap_.has_key(geonameId):
					self.geonameWebDocMap_[geonameId].append(self.makeNodePair(webDocRec[1:4], self.webDocMap_[webDocId]))
				else:
					self.geonameWebDocMap_[geonameId] = [self.makeNodePair(webDocRec[1:4], self.webDocMap_[webDocId])]
					
				
				
			webDocCursor.close()
			

			
		except MySQLdb, e:
			log.error("MySQLdb error %d: %s" % (e.args[0], e.args[1]))
			raise
	
	
	def makeNodePair(self, webDocRef, webDocNode):
		return {'id': webDocNode.getId(),	 		 \
				'text_before': webDocRef[0],         \
			    'text_after': webDocRef[1],          \
			    'weight': webDocRef[2],              \
			    'webdoc_node': webDocNode            \
			   }
		
	
	def getGeonameWebDocMap(self):	
		return self.geonameWebDocMap_
	
	
	